package cn.momoshenchi.handler;


import cn.momoshenchi.util.ParamsException;
import org.springframework.validation.BindException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.method.annotation.MethodArgumentTypeMismatchException;
import org.springframework.web.servlet.ModelAndView;
import org.springframework.web.servlet.view.json.MappingJackson2JsonView;

import javax.servlet.http.HttpServletRequest;

/**
 * @version : 1.0
 * @author: momoshenchi
 * @date: 2021/2/12 - 18:38
 */
@ControllerAdvice
public class GlobalExceptionHandler
{
    /**
     * 难点在于是否json
     *
     * @param e
     * @param request
     * @return
     */
    @ExceptionHandler(value = Exception.class)
    public ModelAndView handle(Exception e, HttpServletRequest request) throws Exception
    {
            e.printStackTrace();
            ModelAndView modelAndView = new ModelAndView(new MappingJackson2JsonView());
            modelAndView.addObject("code", "500");
            modelAndView.addObject("msg", "系统异常请重试");

            if (e instanceof ParamsException)
            {
                ParamsException paramsException = (ParamsException) e;
                modelAndView.addObject("code", paramsException.getCode());
                modelAndView.addObject("msg", paramsException.getMsg());
            }
            else if (e instanceof MethodArgumentTypeMismatchException)
            {
            modelAndView.addObject("code", 300);
            modelAndView.addObject("msg", "参数类型不匹配");
            }
            else if (e instanceof BindException)
            {
                BindException bindException = (BindException) e;
                modelAndView.addObject("code", 500);
                modelAndView.addObject("msg", bindException.getBindingResult().getFieldError().getDefaultMessage());
            }
            return modelAndView;

    }
}
